package com.edu.dao;

import com.edu.bean.PostReply;
import com.edu.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PostReplyDao {

    /**
     * 添加回复
     */
    public boolean add(PostReply reply) {
        String sql = "INSERT INTO post_reply (post_id, user_id, content, create_time) VALUES (?, ?, ?, NOW())";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, reply.getPostId());
            stmt.setInt(2, reply.getUserId());
            stmt.setString(3, reply.getContent());

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除回复
     */
    public boolean delete(Integer replyId) {
        String sql = "DELETE FROM post_reply WHERE reply_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, replyId);
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除帖子的所有回复
     */
    public boolean deleteByPostId(Integer postId) {
        String sql = "DELETE FROM post_reply WHERE post_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询帖子的所有回复
     */
    public List<PostReply> findByPostId(Integer postId) {
        List<PostReply> list = new ArrayList<>();
        String sql = "SELECT r.*, u.username FROM post_reply r " +
                "LEFT JOIN user u ON r.user_id = u.user_id " +
                "WHERE r.post_id = ? ORDER BY r.create_time ASC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                list.add(convertToPostReply(rs));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询帖子的所有回复（包含用户信息）
     */
    public List<Map<String, Object>> findRepliesWithUser(Integer postId) {
        List<Map<String, Object>> list = new ArrayList<>();
        String sql = "SELECT r.*, u.username FROM post_reply r " +
                "LEFT JOIN user u ON r.user_id = u.user_id " +
                "WHERE r.post_id = ? " +
                "ORDER BY r.create_time ASC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("reply_id", rs.getInt("reply_id"));
                map.put("post_id", rs.getInt("post_id"));
                map.put("user_id", rs.getInt("user_id"));
                map.put("content", rs.getString("content"));
                map.put("create_time", rs.getTimestamp("create_time"));
                map.put("username", rs.getString("username"));
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    /**
     * 直接添加回复（不需要创建PostReply对象）
     */
    public boolean addReply(Integer postId, Integer userId, String content) {
        String sql = "INSERT INTO post_reply (post_id, user_id, content, create_time) " +
                "VALUES (?, ?, ?, NOW())";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            stmt.setInt(2, userId);
            stmt.setString(3, content);

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 查询用户的所有回复
     */
    public List<Map<String, Object>> findRepliesByUserId(Integer userId) {
        List<Map<String, Object>> list = new ArrayList<>();
        String sql = "SELECT r.*, u.username, p.title as post_title FROM post_reply r " +
                "LEFT JOIN user u ON r.user_id = u.user_id " +
                "LEFT JOIN post p ON r.post_id = p.post_id " +
                "WHERE r.user_id = ? " +
                "ORDER BY r.create_time DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, userId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("reply_id", rs.getInt("reply_id"));
                map.put("post_id", rs.getInt("post_id"));
                map.put("user_id", rs.getInt("user_id"));
                map.put("content", rs.getString("content"));
                map.put("create_time", rs.getTimestamp("create_time"));
                map.put("username", rs.getString("username"));
                map.put("post_title", rs.getString("post_title"));
                list.add(map);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 查询回复总数
     */
    public int findReplyCount(Integer postId) {
        String sql = "SELECT COUNT(*) FROM post_reply WHERE post_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, postId);
            ResultSet rs = stmt.executeQuery();

            if (rs.next()) {
                return rs.getInt(1);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 将ResultSet转换为PostReply对象
     */
    private PostReply convertToPostReply(ResultSet rs) throws SQLException {
        PostReply reply = new PostReply();
        reply.setReplyId(rs.getInt("reply_id"));
        reply.setPostId(rs.getInt("post_id"));
        reply.setUserId(rs.getInt("user_id"));
        reply.setContent(rs.getString("content"));
        reply.setCreateTime(rs.getTimestamp("create_time"));
        reply.setUsername(rs.getString("username"));
        return reply;
    }
}
